#!/usr/bin/env python

import sys, os, getopt, glob
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
sys.path.append(scriptPath + os.sep + 'lib')
from tiddlywiki import TiddlyWiki


def usage():
	print 'usage: twee [-a author] [-t target] [-m mergefile] [-r rss] source1 [source2..]'


def main (argv):

	# defaults
	
	author = 'twee'
	target = None
	merge = rss_output = ''
	plugins = []
	
	# read command line switches

	try:
		opts, args = getopt.getopt(argv, 'a:m:p:r:t:', ['author=', 'merge=', 'plugins=', 'rss=', 'target='])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
   	
	for opt, arg in opts:
		if (opt in ('-a', '--author')):
			author = arg
		elif (opt in ('-m', '--merge')):
			merge = arg
		elif (opt in ('-p', '--plugins')):
			plugins = arg.split(',')
		elif (opt in ('-r', '--rss')):
			rss_output = arg
		elif (opt in ('-t', '--target')):
			target = arg
	
	# construct a TW object
	
	tw = TiddlyWiki(author)
	
	# read in a file to be merged
	
	if merge != '':
		file = open(merge)
		tw.addHtml(file.read())
		file.close()
	
	# read source files		
	
	sources = []
	
	for arg in args:
		for file in glob.glob(arg):
			sources.append(file)
	
	if len(sources) == 0:
		print 'twee: no source files specified\n'
		sys.exit(2)	
	
	for source in sources:
		file = open(source)		
		tw.addTwee(file.read())
		file.close()

	# generate RSS if requested
	
	if rss_output != '':
		rss_file = open(rss_output, 'w')
		tw.toRss().write_xml(rss_file)
		rss_file.close()
		
	# output the target header

	print tw.toHeader(scriptPath,target)
	
	# the tiddlers
	
	print tw.toHtml()
	
	# plugins
	
	for plugin in plugins:
		file = open(scriptPath + os.sep + 'targets' + os.sep + target \
								+ os.sep + 'plugins' + os.sep + plugin + os.sep + 'compiled.html')
		print(file.read())
		file.close()
	
	# and close it up
	
	print tw.toFooter(scriptPath,target)



if __name__ == '__main__':
	main(sys.argv[1:])
	
